#version 330

struct point_light
{
	vec3 position;
	vec3 color;
	float attenuation0;
	float attenuation1;
	float attenuation2;
	float angle;
};

struct material_properties
{
	vec3 ambient_color;
	vec3 diffuse_color;
	vec3 specular_color;
	float specular_exponent;
};

out vec4 vFragColor;

smooth in vec3  positionInEyeSpace3;
smooth in vec3  normalInEyeSpace;
smooth in vec2  varyingTexCoord;

uniform point_light light1;
uniform material_properties material;
uniform vec3 ambientLight;
uniform sampler2D texture0;
uniform bool doTexture;

void main() {

	vFragColor.rgb = material.ambient_color * ambientLight;
	vec3 toLight = light1.position - positionInEyeSpace3;
	float r = length(toLight);
	float intensity = 1.0 / (light1.attenuation0 + light1.attenuation1*r + light1.attenuation2*r*r);

	vec3 lightDirection = normalize(toLight);
	float diffuse = max(0.0, dot(normalInEyeSpace, lightDirection));
	if(diffuse>0.0) 
	{
        vec3  reflected = normalize(reflect(lightDirection, normalInEyeSpace));
        float specular = max(0.0, dot(reflected, normalize(positionInEyeSpace3)));
        float fSpecular = pow(specular, material.specular_exponent);
        vFragColor.rgb += intensity * fSpecular* light1.color * material.specular_color;
    }
	vFragColor.rgb += diffuse * material.diffuse_color * light1.color;

	if (doTexture)
	{
		vFragColor *= texture(texture0, varyingTexCoord);
	}

	vFragColor.a = 1.0;
}